package com.chhuang.ewcrm.interceptor;

import com.chhuang.ewcrm.config.EwcrmProperties;
import com.chhuang.ewcrm.consts.EwcrmConstants;
import com.chhuang.ewcrm.date.DateUtil;
import com.chhuang.ewcrm.entity.SysUser;
import com.chhuang.ewcrm.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @author chhuang
 * @create 2020-11-28-8:46
 */
@Configuration
public class WLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private EwcrmProperties ewcrmProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ip = request.getRemoteAddr();//本地访问不拦截
        if(StringUtils.isNotEmpty(ip) && ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip) || "localhost".equals(ip))){
            return true;
        }

        String authorization = request.getHeader(EwcrmConstants.HeaderConst.AUTHORIZATION);

        if(StringUtils.isNotEmpty(authorization) && authorization.startsWith("Weigh")){
            String token = authorization.split(" ")[1];
            if(StringUtils.isNotEmpty(token)){
                SysUser user = new SysUser();
                user.setWsLoginToken(token);
                List<SysUser> users = sysUserService.query(user);
                if(users!=null && !users.isEmpty()){
                    user = users.get(0);
                    Date now = new Date();
                    Date lastLoginTime = user.getWsLastLoginTime();
                    Date expTime = DateUtil.getDay(lastLoginTime, ewcrmProperties.getWLoginExpDays());
                    if(expTime.after(now)) return true;
                }
            }
        }

        response.sendRedirect("/wapi/login/relogin");
        return false;
    }
}
